import { getArticleList } from '@/services';
import { IArticleItems } from '@/types';
import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';

export interface ArticleModelState {
  articleList: IArticleItems [],
  articleLength: number
}

export interface ArticleModelType {
  namespace: 'articleRead';
  state: ArticleModelState;
  effects: {
    query: Effect;
    getArticleList: Effect;
  };
  reducers: {
    save: Reducer<ArticleModelState>;
  };
}

const ArticleReadModel: ArticleModelType = {
  // 数据模型，用来隔离数据防止相互影响
  namespace: 'articleRead',

  // 数据模型状态，相当于vuex的state
  state: {
    articleList: [],
    articleLength: 0
  },

  // 异步操作，相当于vuex的action
  effects: {
    // 先简单记忆，*相当于async，yield相当于await
    *query({ payload }, { call, put }) {},
    *getArticleList({payload}, {call, put}){
      let result = yield getArticleList();
      if (result.data){
        yield put({
          type: 'save',
          payload: {
            articleList: result.data[0],
            articleLength: result.data[1]
          }
        })
      }
    }
  },

  // 同步操作，相当于vuex的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },

  }
};

export default ArticleReadModel;